﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

using VTemplate.Engine;
using System.IO;
using MyProFile_V2.Data;
using MyProFile_V2.Model;
using MyProFile_V2.Bll;
using Tickz.Commonz;

using System.Threading;
using Tickz.IOz;

namespace MyProFile_V2
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        #region 加载配置
        private void btn_loadConfig_Click(object sender, EventArgs e)
        {
            string confPath = txt_config.Text;
            if (File.Exists(confPath))
            {//如果存在
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(confPath);
                    XmlElement root = xmlDoc.DocumentElement;
                    //获取数据信息
                    XmlNode dataBaseNode = root.SelectSingleNode("/config/dataBase");
                    string serverIp = dataBaseNode.SelectSingleNode("serverIp").InnerText;
                    string serverPort = dataBaseNode.SelectSingleNode("serverPort").InnerText;
                    string dbName = dataBaseNode.SelectSingleNode("dbName").InnerText;
                    string dbType = dataBaseNode.SelectSingleNode("dbType").InnerText;
                    string userName = dataBaseNode.SelectSingleNode("userName").InnerText;
                    string userPass = dataBaseNode.SelectSingleNode("userPass").InnerText;
                    //获取工程信息
                    XmlNode projectConf = root.SelectSingleNode("/config/projectConf");
                    string projectName = projectConf.SelectSingleNode("projectName").InnerText;
                    string proFileEncode = projectConf.SelectSingleNode("proFileEncode").InnerText;
                    string createProPath = projectConf.SelectSingleNode("createProPath").InnerText;
                   
                    //设置数据信息
                    this.txt_server.Text = serverIp;
                    this.txt_port.Text = serverPort;
                    this.txt_dataName.Text = dbName;
                    this.cb_DBtype.SelectedItem = dbType;
                    this.txt_userName.Text = userName;
                    this.txt_userPass.Text = userPass;
                    //设置工程信息
                    this.txt_proName.Text = projectName;
                    this.cb_encode.SelectedItem = proFileEncode;
                    this.txt_path.Text = createProPath;
                    //设置旧项目路径                  

                }
                catch (Exception ex)
                {
                    MessageBox.Show("出错了：" + ex.Message);
                    throw;
                }
                MessageBox.Show("加载成功");
            }
        }
        #endregion
       
        #region 保存配置
        private void btn_saveConfig_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_config.Text))
            {
                return;
            }
            //保存配置
            string confPath =  txt_config.Text;
            if (!File.Exists(confPath))
            {//如果存在            
                using (File.Create(confPath)) { }
            }

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XmlDeclaration xmlDes = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                xmlDoc.AppendChild(xmlDes);
                XmlElement config = xmlDoc.CreateElement("config");
                xmlDoc.AppendChild(config);

                XmlTextWriter writer = new XmlTextWriter(confPath, Encoding.Default);

                writer.Formatting = Formatting.Indented;
                xmlDoc.WriteTo(writer);
                writer.Flush();
                writer.Close();

                //xmlDoc.Save(confPath);
                xmlDoc.Load(confPath);
                XmlElement root = xmlDoc.DocumentElement;
                //获取数据信息
                XmlNode dataBaseNode = root.SelectSingleNode("/config/dataBase");
                if (dataBaseNode != null)
                {
                    dataBaseNode.RemoveAll();
                }
                else
                {
                    dataBaseNode = root.AppendChild(xmlDoc.CreateElement("dataBase"));
                }
                XmlNode nodeTemp = null;
                nodeTemp = xmlDoc.CreateElement("serverIp");
                nodeTemp.InnerText = this.txt_server.Text;
                dataBaseNode.AppendChild(nodeTemp);
                nodeTemp = xmlDoc.CreateElement("serverPort");
                nodeTemp.InnerText = this.txt_port.Text;
                dataBaseNode.AppendChild(nodeTemp);
                nodeTemp = xmlDoc.CreateElement("dbName");
                nodeTemp.InnerText = this.txt_dataName.Text;
                dataBaseNode.AppendChild(nodeTemp);
                nodeTemp = xmlDoc.CreateElement("dbType");
                nodeTemp.InnerText = this.cb_DBtype.SelectedItem.ToString();
                dataBaseNode.AppendChild(nodeTemp);
                nodeTemp = xmlDoc.CreateElement("userName");
                nodeTemp.InnerText = this.txt_userName.Text;
                dataBaseNode.AppendChild(nodeTemp);
                nodeTemp = xmlDoc.CreateElement("userPass");
                nodeTemp.InnerText = this.txt_userPass.Text;
                dataBaseNode.AppendChild(nodeTemp);
                //获取工程信息
                XmlNode projectConf = root.SelectSingleNode("/config/projectConf");
                if (projectConf != null)
                {
                    projectConf.RemoveAll();
                }
                else
                {
                    projectConf = root.AppendChild(xmlDoc.CreateElement("projectConf"));
                }
                nodeTemp = xmlDoc.CreateElement("projectName");
                nodeTemp.InnerText = this.txt_proName.Text;
                projectConf.AppendChild(nodeTemp);
                nodeTemp = xmlDoc.CreateElement("proFileEncode");
                nodeTemp.InnerText = this.cb_encode.SelectedItem.ToString();
                projectConf.AppendChild(nodeTemp);
                nodeTemp = xmlDoc.CreateElement("createProPath");
                nodeTemp.InnerText = this.txt_path.Text;
                projectConf.AppendChild(nodeTemp);
                //获取旧项目路径
                XmlNode oldProPath = root.SelectSingleNode("/config/oldProPath");
                if (oldProPath != null)
                {
                    oldProPath.RemoveAll();
                }
                else
                {
                    oldProPath = root.AppendChild(xmlDoc.CreateElement("oldProPath"));
                }
                nodeTemp = xmlDoc.CreateElement("hasDiyCode");


                xmlDoc.Save(confPath);


            }
            catch (Exception ex)
            {
                MessageBox.Show("出错了：" + ex.Message);
                throw;
            }
            MessageBox.Show("保存成功");
        }

        #endregion
     
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.txt_server.Text = "127.0.0.1";
            this.txt_port.Text = "1433";
            this.txt_dataName.Text = "dnt31";
            this.txt_userName.Text = "tickwudi";
            this.txt_userPass.Text = "fendou1314";
            //this.btn_submit.Enabled = false;
            this.txt_proName.Text = "DNT31";

            this.txt_path.Text = "e:\\pro2\\";
            //            select * from sysobjects where xtype='u'
            //select * from syscolumns where name='tid'
            //select * from syscolumns where id='357576312'
            cb_DBtype.Items.Add("SQL");
            cb_DBtype.Items.Add("Access");
            cb_DBtype.Items.Add("MySql");
            cb_DBtype.Items.Add("Oracle");
            cb_DBtype.Items.Add("Sqlite");
            cb_DBtype.SelectedIndex = 0;

            cb_encode.SelectedItem = "gb2312";

            this.lb_tabName.Enabled = false;
            this.tv_proTree.Enabled = false;
            this.btn_loadTab.Enabled = false;
            this.btn_loadDefTabConf.Enabled = false;
            this.btn_saveDefTabConf.Enabled = false;
            this.btn_toRight.Enabled = false;
            this.btn_toLeft.Enabled = false;
            this.txt_floderConfig.Text = "cf_xianyang1.xml";
            cb_toolVersion.SelectedIndex = 0;

            this.txt_config.Text = "app_xianyang1.xml";
        }

        private void btn_conn_Click(object sender, EventArgs e)
        {
            string conStr = "server=" + this.txt_server.Text + ";database=" + this.txt_dataName.Text + ";uid=" + this.txt_userName.Text + ";pwd=" + this.txt_userPass.Text;
            DBHelper.ConnectionString = conStr;
            if (DBHelper.IsConn())
            {
                MessageBox.Show("连接成功！");
            }
            else
            {
                MessageBox.Show("连接失败！");
            }
        }

        private void txt_show_Click(object sender, EventArgs e)
        {
            fbd_floder.SelectedPath = this.txt_path.Text;
            if (this.fbd_floder.ShowDialog() == DialogResult.OK)
            {
                this.txt_path.Text = this.fbd_floder.SelectedPath;
            }
        }

        private void btn_OldPath_Click(object sender, EventArgs e)
        {
            fbd_floder.SelectedPath = this.txt_oldPath.Text;
            if (this.fbd_floder.ShowDialog() == DialogResult.OK)
            {
                this.txt_oldPath.Text = this.fbd_floder.SelectedPath;
            }
        }

        private void cb_DBtype_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.txt_port.Enabled = true;
            //改变数据库类型是修改端口
            switch (cb_DBtype.SelectedIndex)
            {
                case 0:
                    this.txt_port.Text = "1433";
                    break;
                case 1:
                    this.txt_port.Text = "0";
                    this.txt_port.Enabled = false;
                    break;
                case 2:
                    this.txt_port.Text = "3306";
                    break;
                case 3:
                    this.txt_port.Text = "8080";
                    break;
                case 4:
                    this.txt_port.Text = "0";
                    this.txt_port.Enabled = false;
                    break;
                default:

                    break;
            }
        }
        #region 文件夹分布
        /// <summary>
        /// 加载按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_loadTab_Click(object sender, EventArgs e)
        {
            //加载表           
            string conStr = "server=" + this.txt_server.Text + ";database=" + this.txt_dataName.Text + ";uid=" + this.txt_userName.Text + ";pwd=" + this.txt_userPass.Text;
            DBHelper.ConnectionString = conStr;
            try
            {
                ArrayList tabList = TableService.getTables();
                foreach (TableModel itme in tabList)
                {
                    if (!lb_tabName.Items.Contains(itme.Name) & tv_proTree.Nodes.Find(itme.Name, true).Length == 0)
                    {
                        lb_tabName.Items.Add(itme.Name);
                    }
                }
                changeButton();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void changeButton()
        {
            if (lb_tabName.Items.Count > 0)
            {
                this.btn_toRight.Enabled = true;

            }
            else
            {
                this.btn_toRight.Enabled = false;

            }
            bool isCanUse = false;
            foreach (TreeNode var in tv_proTree.Nodes)
            {
                if (var.Nodes.Count > 0)
                {
                    isCanUse = true;
                }
            }
            if (isCanUse)
            {
                this.btn_toLeft.Enabled = true;
            }
            else
            {
                this.btn_toLeft.Enabled = false;
            }
        }
        /// <summary>
        /// 是否启用分文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cb_isFloder_CheckedChanged(object sender, EventArgs e)
        {
            //是否分文件夹
            if (this.cb_isFloder.Checked)
            {
                this.lb_tabName.Enabled = true;
                this.tv_proTree.Enabled = true;
                this.btn_loadTab.Enabled = true;
                this.btn_loadDefTabConf.Enabled = true;
                this.btn_saveDefTabConf.Enabled = true;
                changeButton();
            }
            else
            {
                this.lb_tabName.Enabled = false;
                this.tv_proTree.Enabled = false;
                this.btn_loadTab.Enabled = false;
                this.btn_loadDefTabConf.Enabled = false;
                this.btn_saveDefTabConf.Enabled = false;
                this.btn_toRight.Enabled = false;
                this.btn_toLeft.Enabled = false;
            }
        }
        /// <summary>
        /// 用来加载新表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_loadDefTabConf_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("加载后原来的配置被覆盖，确定要加载么？", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }
            string confPath = txt_floderConfig.Text;
            lb_tabName.Items.Clear();
            tv_proTree.Nodes.Clear();
            if (File.Exists(confPath))
            {//如果存在
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(confPath);
                    XmlElement root = xmlDoc.DocumentElement;
                    //获取表名
                    XmlNode table = root.SelectSingleNode("/config/table");

                    foreach (XmlNode var in table.ChildNodes)
                    {
                        lb_tabName.Items.Add(var.InnerText);
                    }
                    //获取工程文件夹
                    XmlNode projectFloder = root.SelectSingleNode("/config/proFloder");

                    foreach (XmlElement var in projectFloder.ChildNodes)
                    {
                        TreeNode tn = new TreeNode();
                        tn.Text = var.GetAttribute("fName");
                        tn.Name = var.GetAttribute("fName");

                        foreach (XmlElement var2 in var.ChildNodes)
                        {
                            TreeNode tn2 = new TreeNode();
                            tn2.Text = var2.InnerText;
                            tn2.Name = var2.InnerText;
                            tn.Nodes.Add(tn2);
                        }
                        tv_proTree.Nodes.Add(tn);
                    }
                    changeButton();
                    tv_proTree.ExpandAll();
                    MessageBox.Show("加载成功");
                }
                catch (Exception)
                {
                    MessageBox.Show("读取配置文件错误");
                }


            }
            else
            {//不存在
                MessageBox.Show("不存在配置文件:" + txt_floderConfig.Text);
            }
        }

        /// <summary>
        /// 保存 文件夹配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_saveDefTabConf_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("保存后原来的配置被覆盖，确定要保存么？", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }
            //保存配置
            string confPath = txt_floderConfig.Text;
            if (!File.Exists(confPath))
            {//如果存在
                using (File.Create(confPath)) { }
            }

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XmlDeclaration xmlDes = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                xmlDoc.AppendChild(xmlDes);
                XmlElement config = xmlDoc.CreateElement("config");
                xmlDoc.AppendChild(config);
                xmlDoc.Save(confPath);
                xmlDoc.Load(confPath);
                XmlElement root = xmlDoc.DocumentElement;
                //获取表名
                XmlNode table = root.SelectSingleNode("/config/table");
                if (table != null)
                {
                    table.RemoveAll();
                }
                else
                {
                    table = root.AppendChild(xmlDoc.CreateElement("table"));
                }
                foreach (string var in lb_tabName.Items)
                {
                    XmlNode name = xmlDoc.CreateElement("name");
                    name.InnerText = var;
                    table.AppendChild(name);
                }
                //获取工程文件夹
                XmlNode projectFloder = root.SelectSingleNode("/config/proFloder");
                if (projectFloder != null)
                {
                    projectFloder.RemoveAll();
                }
                else
                {
                    projectFloder = root.AppendChild(xmlDoc.CreateElement("proFloder"));
                }
                foreach (TreeNode var in tv_proTree.Nodes)
                {
                    XmlElement floder = xmlDoc.CreateElement("floder");
                    floder.SetAttribute("fName", var.Text);
                    foreach (TreeNode var2 in var.Nodes)
                    {
                        XmlNode name = xmlDoc.CreateElement("name");
                        name.InnerText = var2.Text;
                        floder.AppendChild(name);
                    }
                    projectFloder.AppendChild(floder);
                }

                xmlDoc.Save(confPath);
                changeButton();
                MessageBox.Show("保存成功");

            }
            catch (Exception ex)
            {
                MessageBox.Show("保存报异常");
            }
        }
        /// <summary>
        /// 向右
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_toRight_Click(object sender, EventArgs e)
        {
            if (lb_tabName.SelectedItem == null)
            {
                MessageBox.Show("请选择相应的表");
            }
            else if (tv_proTree.SelectedNode == null)
            {
                MessageBox.Show("请选择相应的文件夹");
            }
            else if (tv_proTree.SelectedNode.Parent != null)
            {
                MessageBox.Show("请选择相应的文件夹");
            }
            else
            {
                TreeNode tn = new TreeNode();
                tn.Name = lb_tabName.SelectedItem.ToString();
                tn.Text = lb_tabName.SelectedItem.ToString();
                tv_proTree.SelectedNode.Nodes.Add(tn);
                lb_tabName.Items.Remove(lb_tabName.SelectedItem);
                if (lb_tabName.Items.Count > 0)
                {
                    lb_tabName.SelectedIndex = 0;
                }
                tv_proTree.SelectedNode.Expand();
                changeButton();



            }
        }
        /// <summary>
        /// 向左
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_toLeft_Click(object sender, EventArgs e)
        {
            if (tv_proTree.SelectedNode == null)
            {
                MessageBox.Show("请选择相应的文件");
            }
            else
            {
                TreeNode tn = tv_proTree.SelectedNode.Parent;
                if (tn != null)
                {
                    lb_tabName.Items.Add(tv_proTree.SelectedNode.Text);
                    tv_proTree.SelectedNode.Remove();
                    if (tn.FirstNode != null)
                    {
                        tv_proTree.SelectedNode = tn.FirstNode;
                    }
                }


                changeButton();
            }
        }

        /// <summary>
        /// 在树上点右键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tv_proTree_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point point = tv_proTree.PointToClient(Cursor.Position);
                TreeViewHitTestInfo info = tv_proTree.HitTest(point.X, point.Y);
                tv_proTree.SelectedNode = info.Node;

                cms_del.Enabled = true;
                cms_upd.Enabled = true;
                tv_proTree.ContextMenuStrip = cms_proTreeFloder;

                if (this.tv_proTree.SelectedNode == null)
                {
                    cms_del.Enabled = false;
                    cms_upd.Enabled = false;
                }
                else
                {
                    if (tv_proTree.SelectedNode.Parent != null)
                    {
                        cms_del.Enabled = false;
                        cms_upd.Enabled = false;
                    }
                    if (tv_proTree.SelectedNode.Nodes.Count > 0)
                    {
                        cms_del.Enabled = false;
                    }
                }


                //TreeNode tn = this.tv_proTree.SelectedNode.Parent;
                //if (tv_proTree.ContextMenuStrip == null)
                //{
                //    tv_proTree.ContextMenuStrip = cms_proTreeFloder;
                //}
                //else
                //{
                //    tv_proTree.ContextMenuStrip = cms_proTreeFloder;
                //}

                //TreeNode tn = tv_proTree.GetNodeAt(e.X, e.Y);
                //if (tn != null)
                //{
                //    this.tv_proTree.SelectedNode = tn;
                //}

            }
        }

        private void cms_add_Click(object sender, EventArgs e)
        {
            //右键添加 
            FloderDo fd = new FloderDo();
            fd.ShowDialog(this);
            fd.Dispose();
        }

        private void cms_upd_Click(object sender, EventArgs e)
        {
            //修改
            FloderDo fd = new FloderDo();
            fd.IsEdit = true;//标示 修改数据
            fd.ShowDialog(this);
            fd.Dispose();
        }

        private void cms_del_Click(object sender, EventArgs e)
        {
            //删除
            if (tv_proTree.SelectedNode == null)
            {
                MessageBox.Show("请选择一个节点");
            }
            else
            {
                if (tv_proTree.SelectedNode.Nodes.Count == 0)
                {
                    tv_proTree.SelectedNode.Remove();
                }
                else
                {
                    MessageBox.Show("请确保该节点无子节点");
                }

            }
        }
        #endregion

        /// <summary>
        /// 生成抽象工厂
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_CreateAbstractFactory_Click(object sender, EventArgs e)
        {
            //生成抽象工厂
            string conStr = "server=" + this.txt_server.Text + ";database=" + this.txt_dataName.Text + ";uid=" + this.txt_userName.Text + ";pwd=" + this.txt_userPass.Text;
            DBHelper.ConnectionString = conStr;
            ProInfoModel proInfo = new ProInfoModel();
            //项目名称
            proInfo.ProName = Stringz.ToPascal(this.txt_proName.Text);
            //生成项目的路径
            proInfo.ProPath = this.txt_path.Text;
            //数据库类型
            proInfo.DbType = this.cb_DBtype.Text.ToString();
            //文件编码
            proInfo.FileEncode = this.cb_encode.SelectedItem.ToString();
            //不生成的表
            proInfo.SkipTable = this.txt_scapTab.Text;
            //公司
            proInfo.CompanyInfo = this.txt_company.Text;
            //版权
            proInfo.CopyRight = this.txt_copyRight.Text;
            //作者
            proInfo.ProAuthor = this.txt_author.Text;
            //是否选择了旧项目
            if (string.IsNullOrEmpty(txt_oldPath.Text))
            {
                proInfo.IsHasOld = false;
            }else{
                proInfo.IsHasOld = true;
            }
            
            //是否分文件夹
            proInfo.IsProFloder = cb_isFloder.Checked;
            //开发版本
            proInfo.ToolVersion = cb_toolVersion.Text;
            //数据库设置
            proInfo.DbServer = txt_server.Text;
            proInfo.DbName = txt_dataName.Text;
            proInfo.DbUid = txt_userName.Text;
            proInfo.DbPass = txt_userPass.Text;
            if (proInfo.IsProFloder)
            {//如果选择了，分文件夹
                Hashtable has = new Hashtable();
                foreach (TreeNode var in tv_proTree.Nodes)
                {
                    foreach (TreeNode var2 in var.Nodes)
                    {
                        has.Add(var2.Name, var.Name);
                    }
                }
                proInfo.TabToFloderHas = has;
            }
           
            Buildup buildUp = new Buildup(proInfo);
            buildUp.setUp();
            MessageBox.Show("生成成功！");
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
        }

        private void tab_ProConfig_Click(object sender, EventArgs e)
        {

        }

        private void btn_configFile_Click(object sender, EventArgs e)
        {
            ofd_File.Filter = "app_*.xml|app_*.xml";
            
            if (this.ofd_File.ShowDialog() == DialogResult.OK)
            {
                this.txt_config.Text = this.ofd_File.FileName;
            }
        }

        private void btn_floderConfig_Click(object sender, EventArgs e)
        {
            ofd_File.Filter = "cf_*.xml|cf_*.xml";

            if (this.ofd_File.ShowDialog() == DialogResult.OK)
            {
                this.txt_floderConfig.Text = this.ofd_File.FileName;
            }
        }

        
        
        
    }
}